<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item>物品管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">
        <a-tabs :active-key="tabIndex" animated type="card" @change="changeTab">
          <a-tab-pane v-for="(tab, index) in tabList" :key="index" :tab="tab.name">
            <div class="filter">
              <a-form>
                <a-row>
                  <a-col :lg="16" :md="[16, 16, 24, 24][index]" :xs="24">
                    <a-col :lg="[12, 12, 24, 12][index]" :md="index > 2 ? 12 : 24" :xs="24">
                      <div v-if="index === 2">
                        <a-form-item label="所属区域" v-bind="formItemLayout">
                          <a-row style="width: 100%" :gutter="12">
                            <a-col :md="12" :xs="24">
                              <a-select v-model="tempQueryParam[index].area_id" placeholder="请选择区域">
                                <a-select-option
                                  v-for="item in areaList"
                                  :key="item.id"
                                  :value="item.id"
                                >{{ item.name }}</a-select-option>
                              </a-select>
                            </a-col>
                            <a-col :md="12" :xs="24">
                              <a-select
                                v-model="tempQueryParam[index].area_pid"
                                :disabled="!tempQueryParam[index].area_id"
                                :placeholder="tempQueryParam[index].area_id ? '请选择子区域' : '请选择区域'"
                              >
                                <a-select-option
                                  v-for="item in childAreaList"
                                  :key="item.id"
                                  :value="item.id"
                                >{{ item.name }}</a-select-option>
                              </a-select>
                            </a-col>
                          </a-row>
                        </a-form-item>
                        <a-form-item label="物品名称" v-bind="formItemLayout">
                          <a-row style="width: 100%" :gutter="12">
                            <a-col :md="12" :xs="24">
                              <a-input v-model="tempQueryParam[index].goodsName" placeholder="请输入" />
                            </a-col>
                          </a-row>
                        </a-form-item>
                      </div>

                      <a-form-item v-else-if="index === 3" label="一级分类" v-bind="formItemLayout">
                        <a-select v-model="tempQueryParam[index].firId" placeholder="请选择一级分类">
                          <a-select-option
                            v-for="item in firTypeList"
                            :key="item.code"
                            :value="item.id"
                          >{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-item>

                      <a-form-item v-else label="物品编号" v-bind="formItemLayout">
                        <a-input
                          v-model="tempQueryParam[index].code"
                          allow-clear
                          placeholder="请输入"
                        />
                      </a-form-item>
                    </a-col>

                    <a-col v-if="!/2/.test(index)" :lg="12" :md="index > 2 ? 12 : 24" :xs="24">
                      <a-form-item :label="index > 1 ? '二级分类' : '物品名称'" v-bind="formItemLayout">
                        <a-select
                          v-if="index === 3"
                          v-model="tempQueryParam[index].secId"
                          :disabled="!tempQueryParam[index].firId"
                          :placeholder="`请选择${tempQueryParam[index].firId ? '二级' : '一级'}分类`"
                        >
                          <a-select-option
                            v-for="item in $get(itemSecTypeListMaps, tempQueryParam[index].firId, [])"
                            :key="item.code"
                            :value="item.id"
                          >{{ item.name }}</a-select-option>
                        </a-select>

                        <a-input
                          v-else
                          v-model="tempQueryParam[index].name"
                          allow-clear
                          placeholder="请输入"
                        />
                      </a-form-item>
                    </a-col>

                    <a-col v-if="!/2/.test(index)" :lg="12" :sm="24">
                      <div v-show="index < 2" class="btns btn-container">
                        <a-button type="primary" @click="handleAdd">
                          <a-icon type="plus" />新增物品
                        </a-button>
                        <a-button @click="clickImport">物品导入</a-button>
                      </div>
                      <div v-show="index === 3" class="btns btn-container">
                        <a-button type="primary" @click="handleAddType(1)">
                          <a-icon type="plus" />新增一级分类
                        </a-button>
                        <a-button @click="handleAddType(2)">
                          <a-icon type="plus" />新增二级分类
                        </a-button>
                      </div>
                    </a-col>
                  </a-col>

                  <a-col :lg="8" :md="8" :sm="[12, 12, 24, 24][index]" :xs="24">
                    <div class="btns btn-container">
                      <a-button type="primary" @click="handleSearch(index)">查询</a-button>
                      <a-button @click="reset">重置</a-button>
                      <a-button
                        v-if="index < 3"
                        :loading="sending"
                        @click="handleExport(index)"
                      >导出报表</a-button>
                      <a-button v-if="index === 2" @click="$router.push('item/history')">往期记录</a-button>
                    </div>
                  </a-col>
                </a-row>
              </a-form>
            </div>

            <s-table
              :ref="`table${index}`"
              class="s-table"
              bordered
              :row-selection="index > 1 ? null : { onChange }"
              row-key="index"
              :locale="{ emptyText: '暂无数据' }"
              :show-pagination="false"
              :columns="columns[index]"
              :data="loadData[index]"
              :scroll="{ y: index > 1 ? scrollY : false }"
              :alert="false"
            >
              <template slot="categories" slot-scope="item">
                <span v-if="item.firName">{{ item.firName }}</span>
                <span v-if="item.firName && item.secName">></span>
                <span v-if="item.secName">{{ item.secName }}</span>
              </template>
              <template slot="code" slot-scope="item">{{ item.secCode || item.firCode }}</template>
              <template slot="firName" slot-scope="item">
                <div>{{ item.firName }}<span class="primary-link" style="padding-left: 12px;" @click="handleEdit(item, 1)">编辑</span></div>
              </template>
              <template slot="secName" slot-scope="item">
                <div v-if="item.secName">{{ item.secName }}<span class="primary-link" style="padding-left: 12px;" @click="handleEdit(item, 2)">编辑</span></div>
                <span v-else>/</span>
              </template>
              <template slot="action" slot-scope="item">
                <div class="action-container">
                  <span v-if="/0|1|2/.test(index)" class="success-link" @click="showDetail(item)">详情</span>
                  <span
                    v-if="/0|1|3/.test(index)"
                    class="danger-link"
                    @click="handleDel(item, index)"
                  >删除</span>
                </div>
              </template>
            </s-table>
            <!-- 分页器 -->
            <div v-if="/0|1/.test(index)" class="pagination-container">
              <a-pagination
                :page-size="queryParam[index].pageSize"
                :show-total="
                  total =>
                    `共${total}条记录 第${
                      queryParam[index].pageNum
                    }/${Math.ceil(total / queryParam[index].pageSize)}页`
                "
                :current="queryParam[index].pageNum"
                :total="count[index]"
                hide-on-single-page
                show-quick-jumper
                @change="handlePage"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-card>

    <!-- 导入弹窗 -->
    <a-modal v-model="showUpload" title="物品导入">
      <a-row>
        <a-form-item label="下载模板" v-bind="formItemLayout">
          <a class="primary-link" download="物品导入模板.xlsx" href="/template.xlsx">下载模板</a>
        </a-form-item>
      </a-row>
      <a-row>
        <a-form-item label="上传文件" v-bind="formItemLayout">
          <a-upload
            accept=".xlsx"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :custom-request="handleUpload"
          >
            <a v-if="!tempFile" class="primary-link">选择文件</a>
            <a v-else class="primary-link">{{ tempFile.name }}</a>
          </a-upload>
        </a-form-item>
      </a-row>
      <template slot="footer">
        <a-button @click="showUpload = false">取消</a-button>
        <a-button :loading="sending" class="primary-btn" @click="handleImport">导入</a-button>
      </template>
    </a-modal>
    <!-- 导入弹窗 end -->

    <a-modal
      v-model="showTypeEdit"
      :title="
        `${$get(targetType, 'id') ? '编辑' : '新增'}${
          targetLevel < 2 ? '一' : '二'
        }级分类`
      "
      :after-close="afterClose"
    >
      <a-form :form="form">
        <a-form-item v-if="targetLevel > 1" label="一级分类名称" required v-bind="formItemLayout">
          <a-select
            v-decorator="['pid', { rules: [{ required: true, type: 'number', message: '请选择一级分类', whitespace: true }] }]"
            placeholder="请选择一级分类"
          >
            <a-select-option
              v-for="item in firTypeList"
              :key="item.id"
              :value="item.id"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label="`${targetLevel < 2 ? '一' : '二'}级分类名称`"
          required
          v-bind="formItemLayout"
        >
          <a-input
            v-decorator="['name', { rules: [{ required: true, type: 'string', message: '请输入', whitespace: true }] }]"
            placeholder="请输入"
          />
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="showTypeEdit = false">取消</a-button>
        <a-button :loading="sending" class="primary-btn" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
    <!-- 新增、编辑 类别弹窗 end -->

    <a-modal
      v-model="showDeleteType"
      title="删除分类"
      centered
      @ok="deleteItem(tempItem, 3)"
    >
      <div class="ant-modal-confirm-body">
        <a-icon type="exclamation-circle" theme="filled" class="anticon anticon-question-circle" style="color: #faad14" />
        <div class="ant-modal-confirm-title">确定删除选中的分类?</div>
        <div class="ant-modal-confirm-content alarm-text">删除后，关联的物品也一并删除，请谨慎操作。</div>
      </div>
    </a-modal>

  </page-view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { PageView, STable } from '@/components'

const assetsColumns = [
  { title: '物品编号', align: 'center', dataIndex: 'code' },
  { title: '物品名称', align: 'center', dataIndex: 'name' },
  { title: '所属分类', align: 'center', scopedSlots: { customRender: 'categories' }},
  { title: '规格型号', align: 'center', dataIndex: 'model' },
  { title: '当前库存', align: 'center', dataIndex: 'quantity' },
  { title: '单位', align: 'center', dataIndex: 'unit' },
  { title: '操作', align: 'center', width: '150px', scopedSlots: { customRender: 'action' }}
]
const areaColumns = [
  { title: '物品编号', width: '10%', align: 'center', dataIndex: 'code' },
  { title: '物品名称', width: '12%', align: 'center', dataIndex: 'goodsName' },
  { title: '所属区域', align: 'center', dataIndex: 'deptName' },
  { title: '上期结存', width: '106px', align: 'center', dataIndex: 'lastBalance' },
  { title: '本期领入', width: '106px', align: 'center', dataIndex: 'receive' },
  { title: '本期减少', width: '106px', align: 'center', dataIndex: 'reduce' },
  { title: '本期结存', width: '106px', align: 'center', dataIndex: 'balance' }
  // { title: '操作', width: '84px', align: 'center', scopedSlots: { customRender: 'action' }}
]
const typeColumns = [
  { title: '分类编号', width: '12%', align: 'center', scopedSlots: { customRender: 'code' }},
  { title: '一级分类', width: '30%', align: 'center', scopedSlots: { customRender: 'firName' }},
  { title: '二级分类', width: '35%', align: 'center', scopedSlots: { customRender: 'secName' }},
  { title: '分类物品数量', width: '15%', align: 'center', dataIndex: 'qty' },
  { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
]

export default {
  name: 'Item',
  components: { PageView, STable },
  inject: ['formItemLayout'],

  async fetch ({ store, app }) {
    store.dispatch('property/getItemTypes')
    const list = []
    const { $get } = store
    // if (!$get(store, 'state.basic.deptList.length')) list.push({ fn: app.$departmentListFunc })
    if (!$get(store, 'state.basic.areaList.length')) list.push({ fn: app.$areaListFunc })
    await app.$requestList(list)
    store.dispatch('basic/setDeptArea')
  },

  async asyncData ({ app, $axios }) {
    const areaList = await $axios.post('api/area/queryAll', { pid: 0 }).then(res => app.$get(res, 'data.data', [])).catch(e => [])
    return { areaList }
  },

  data () {
    return {
      sending: false,
      scrollY: 400,

      tempQueryParam: [
        { code: undefined, name: undefined },
        { code: undefined, name: undefined },
        { area_id: undefined, area_pid: undefined, goodsName: undefined },
        { firId: undefined, secId: undefined }
      ],

      tabList: [
        { name: '固定资产' },
        { name: '非固定资产' },
        { name: '区域资产查询' },
        { name: '类别管理' }
      ],

      columns: [assetsColumns, assetsColumns, areaColumns, typeColumns],
      count: [0, 0, 0, 0],
      list: [],

      loadData: [
        this.loadAssets,
        this.loadAssets,
        this.loadArea,
        this.loadType
      ],

      // 类别管理
      form: this.$form.createForm(this),
      showTypeEdit: false,
      targetType: {},
      targetLevel: 0,
      showDeleteType: false,
      tempItem: null,

      showUpload: false,
      tempFile: null,

      rowIds: [],
      rowItems: [],

      childAreaList: []
    }
  },

  computed: {
    ...mapState({
      tabIndex: state => state.property.tabIndex,
      queryParam: state => state.property.queryParam,
      firTypeList: state => state.property.itemFirTypeList,
      itemSecTypeListMaps: state => state.property.itemSecTypeListMaps
      // deptList: state => state.basic.deptList,
      // deptListMaps: state => state.basic.deptListMaps
    })
  },

  watch: {
    queryParam: {
      handler (list) {
        list.forEach((obj, index) => {
          const target = this.tempQueryParam[index]
          for (const key in target) {
            target[key] = obj[key]
          }
        })
        this.$forceUpdate()
      },
      immediate: true,
      deep: true
    },

    async 'tempQueryParam.2.area_id' (pid = -1) {
      this.tempQueryParam[2].area_pid = undefined
      if (pid === -1) return false
      const { childAreaList, $get, $axios } = this
      childAreaList.splice(0)
      const list = await $axios.post('api/area/queryAll', { pid }).then(res => $get(res, 'data.data', [])).catch(e => [])
      childAreaList.push(...list)
    },

    'tempQueryParam.3.firId' () {
      Object.assign(this.tempQueryParam, { secId: undefined })
      // const target = this.queryParam[3]
      // const value = { secId: undefined }
      // this.setQueryParam({ target, value })
    },

    tabIndex (index) {
      this.refresh(index)
    }
  },

  mounted () {
    if (!process.client) return false
    const viewHeight = document.querySelector('.ant-layout-content').offsetHeight
    this.scrollY = viewHeight - 64 - 55 - 12 * 2 - 24 * 2 - 56 - 108 - 62
    if (this.scrollY < 0) this.scrollY = 600
  },

  methods: {
    ...mapActions('property', ['getItemTypes', 'tabChange', 'setQueryParam']),

    async handleImport () {
      if (this.sending) return false
      const file = this.tempFile
      const { $message, $axios, $get } = this
      if (!file) return $message.error('无法上传')

      this.$toggleSending(1)

      const formData = new FormData()
      formData.append('file', file)
      formData.append('Content-Type', 'multipart/form-data')

      const res = await $axios
        .post('api/assetsGoods/importGoods', formData)
        .then(res => res)
        .catch(e => false)

      this.$toggleSending()
      $message.destroy()
      if ($get(res, 'data.code', false) !== '000000') {
        return $message.error($get(res, 'data.data.0', '请稍后再试'))
      }
      $message.info('导入成功')
      this.showUpload = false
    },

    handleUpload ({ file }) {
      this.tempFile = file
    },

    beforeUpload (file) {
      const isXlsx = /\.xlsx$/.test(file.name)
      if (!isXlsx) this.$message.error('请选择xlsx文件!')
      return isXlsx
    },

    changeTab (value) {
      this.tabChange({ value })
    },

    handlePage (pageNum = 1) {
      const { queryParam, refresh, tabIndex, setQueryParam } = this
      setQueryParam({ target: queryParam[tabIndex], value: { pageNum }})
      refresh(tabIndex)
    },

    clickImport () {
      this.tempFile = null
      this.showUpload = true
    },

    // 导出报表
    async handleExport (index) {
      const { rowIds, rowItems, $message, handleParams } = this
      if (!rowItems.length) {
        $message.destroy()
        $message.error('请选择要导出的报表')
        return false
      }

      this.$toggleSending(1)
      const param = handleParams()
      if (index < 2) param.type = index + 1
      param.ids = rowItems.map(i => i.id).join(',')
      param.pageNum = undefined
      param.pageSize = undefined
      const fileName = index === 2 ? `区域资产报表_${Date.now()}` : `${index > 0 ? '非' : ''}固定资产报表_${Date.now()}`
      const url = index === 2 ? 'assetsInventory/exportRegionalAssetsList' : 'assetsGoods/export'
      const bool = await this.$exportFile({ url: `api/${url}`, param, fileName })
      if (bool) {
        rowIds.splice(0)
        rowItems.splice(0)
      }
      this.$toggleSending()
    },

    handleParams () {
      const { queryParam, tabIndex } = this
      const res = {}
      const params = queryParam[tabIndex]
      for (const key in params) {
        const item = params[key]
        if (item) res[key] = item
      }
      return res
    },

    loadType () {
      const { handleParams, $axios, $get, getItemTypes, $findindex } = this
      const params = handleParams()
      const loadRes = { data: [] }
      getItemTypes()

      return $axios.post('api/assetsCategory/queryQty', params).then(res => {
        $get(res, 'data.data.dataList', []).map(i => {
          const { firId, secId, qty } = i
          const index = $findindex(loadRes.data, i => i.firId === firId && i.secId === secId)
          if (index > -1) Object.assign(loadRes.data[index], { qty: loadRes.data[index].qty + qty })
          else loadRes.data.push(Object.assign(i, { index: loadRes.data.length }))
        })
        return loadRes
      })
        .catch(e => loadRes)
    },

    loadArea () {
      const { handleParams, $axios, $get } = this
      const params = handleParams()
      // if (params.deptId) {
      //   params.area_pid = params.deptId
      //   delete params.deptId
      // }
      const loadRes = { data: [] }

      return $axios
        .post('api/assetsInventory/regionalAssetsList', params)
        .then(res => {
          loadRes.data = $get(res, 'data.data', []).map((i, index) =>
            Object.assign(i, { index })
          )
          return loadRes
        })
        .catch(e => loadRes)
    },

    loadAssets () {
      const { handleParams, $axios, $get, count, tabIndex, list } = this
      const params = handleParams()
      const loadRes = { data: [] }

      list.splice(0)
      return $axios
        .post('api/assetsGoods/query', params)
        .then(res => {
          loadRes.data = $get(res, 'data.data.dataList', []).map((i, index) => Object.assign(i, { index }))
          list.push(...loadRes.data)
          count.splice(tabIndex, 1, $get(res, 'data.data.count', 0))
          return loadRes
        })
        .catch(e => loadRes)
    },

    reset () {
      const { queryParam, tabIndex, rowIds, rowItems } = this
      const target = queryParam[tabIndex]
      const value = {}
      for (const key in target) {
        if (!/page|type/.test(key)) value[key] = undefined
      }
      rowIds.splice(0)
      rowItems.splice(0)
      this.setQueryParam({ target, value })
    },

    /**
     * 添加/修改 物品类别
     */
    handleOk () {
      if (this.sending) return false
      const {
        targetType,
        form,
        targetLevel,
        $axios,
        $message,
        refresh,
        firTypeList,
        itemSecTypeListMaps,
        $get
      } = this
      const { firId, secId } = targetType
      form.validateFields(async (err, { name, pid }) => {
        if (err) return false
        const params = { name, pid: -1, isDelete: 0 }
        if (targetLevel > 1) params.pid = pid
        let success = true
        console.log(firId)
        if (!firId) {
          // 新增
          $message.destroy()
          this.$toggleSending(1)
          success = await $axios
            .post('api/assetsCategory/', params)
            .then(res => {
              if (res.data.code === '000000') return true
              else return false
            })
            .catch(e => false)
        } else {
          // 修改
          console.log('edit', firId)
          firTypeList.some(({ id }) => {
            console.log(id, targetLevel)
            if (id === firId) {
              if (targetLevel > 1) {
                return $get(itemSecTypeListMaps, id, []).some(({ id }) =>
                  id === secId ? (params.id = id) : false
                )
              } else return (params.id = id)
            }
          })
          if (params.id) {
            success = await $axios
              .put(`api/assetsCategory/${params.id}`, params)
              .then(res => {
                if (res.data.code === '000000') return true
                else return false
              })
              .catch(e => false)
          }
        }
        // 完成提示
        this.$toggleSending()
        if (success) {
          $message.info(`${firId ? '修改' : '添加'}成功`)
          refresh(3)
          this.showTypeEdit = false
        } else {
          $message.error('请稍后再试')
        }
      })
    },

    afterClose () {
      this.targetType = {}
      this.targetLevel = 0
      this.form.resetFields()
    },

    handleAddType (level = 1) {
      this.targetLevel = level
      this.showTypeEdit = true
    },

    // 修改物品类别
    handleEdit (targetType, targetLevel = 1) {
      Object.assign(this, { targetType, targetLevel })
      const values = {}
      values.name = this.$get(
        targetType,
        ['name', 'firName', ['secName']][targetLevel],
        undefined
      )
      if (targetLevel > 1) values.pid = targetType.firId
      this.showTypeEdit = true
      this.$nextTick(_ => {
        this.form.setFieldsValue(values)
      })
    },

    onChange (ids, items) {
      this.rowIds = ids
      this.rowItems = items
    },

    handleDel (item, index) {
      this.tempItem = null
      if (index > 2) {
        this.showDeleteType = true
        this.tempItem = item
        return
      }
      const { deleteItem } = this
      this.$confirm({
        centered: true,
        maskClosable: true,
        title: '删除物品',
        content: '确定删除选中的物品？',
        onOk () {
          deleteItem(item, index)
        }
      })
    },

    async deleteItem (item, index) {
      this.showDeleteType = false
      const { $axios, $message, $get, refresh, setQueryParam, list, queryParam, tabIndex } = this
      const { firId, secId } = item
      const url = /3/.test(index) ? 'assetsCategory' : 'assetsGoods'
      let id = ''
      this.$toggleSending(1)
      if (/3/.test(index) && firId) id = secId || firId
      // 类别删除
      else id = item.id // 删除物品
      $message.destroy()
      if (!id) return $message.error('请稍后再试')
      const res = await $axios.delete(`api/${url}/${id}`).then(res => res).catch(e => 1)
      this.$toggleSending()
      if ($get(res, 'data.code') !== '000000') return $message.error($get(res, 'data.mesg', '请稍后再试'))
      const pageNum = $get(queryParam[tabIndex], 'pageNum', 1)
      if (list.length < 2 && pageNum > 1) setQueryParam({ target: queryParam[tabIndex], value: { pageNum: pageNum - 1 }})
      refresh(index)
      return $message.info('已删除')
    },

    // 刷新表单
    refresh (index = -1) {
      if (index === -1) return false
      this.rowIds.splice(0)
      this.rowItems.splice(0)
      const table = this.$get(this.$refs, `table${index}.0`, {})
      table && table.refresh && table.refresh()
    },

    showDetail (item) {
      this.$router.push(`item/detail/${item.id}`)
    },

    showDataDetail (item) {
      this.showDataModal = true
    },

    handleAdd () {
      this.$router.push('item/add')
    },

    // 点击搜索
    handleSearch (index) {
      const { queryParam, refresh, setQueryParam, tempQueryParam } = this
      const value = tempQueryParam[index]
      const target = queryParam[index]
      if (index < 2) value.pageNum = 1
      setQueryParam({ target, value })
      refresh(index)
    }
  }
}
</script>

<style lang="less" scoped>
.filter {
  .btns {
    text-align: left;

    button {
      margin-bottom: 6px;
    }
  }
}

.action-container {
  .Flex;
  .Flex-center;
}

.alarm-text {
  color: @red-6;
}
</style>
